/**
 * 定义冻结表格行列的工具类模块
 */
(function(window, angular, undefined){

	var Module = angular.module('water.common.freezeGrid',['waterCommon']);
	
	/**
	 * 冻结表格，实现表格宽高度自动计算
	 */
	Module.directive("freezeGrid", function($freezeGridService) {
		return {
		    restrict: "A",     
		    scope: {              
		    	headRowlength:"@", //表头的行数
		    	timeColumnLength:"@",//时间列数
			    freezeBoxHeight:"@",//容纳表格容器的高度
			    freezeBoxWidth:"@",//容纳表格容器的宽度
			    freezeTimecellWidth:'@',//时间列的宽度
			    freezeDatacellWidth:'@',//数据列的宽度
			    freezeCellHeight:'@',//数列的高度
			    componentObject:"=componentObject"
		    },
		    controller: [ "$scope", function ($scope) {
		    	
		    }], 
		    link:function($scope, elm, attrs, controller){
		    	/**
		    	 * 表头有几行，直接影响长宽高计算
		    	 */
		    	$scope.headRowlength = attrs.headRowlength;
		    	/**
		    	 * 需要冻结的时间列的列数，默认为1
		    	 */
		    	$scope.timeColumnLength = attrs.timeColumnLength;
		    	if(!$scope.timeColumnLength){
		    		$scope.timeColumnLength = 1;
		    	}
		    	
		    	/**
		    	 * 表格外包div的高度，如果此高度比表格的高度小，则出现滚动条
		    	 */
		    	$scope.freezeBoxHeight = eval($scope.freezeBoxHeight);
		    	/**
		    	 * 表格外包div的宽度，同上
		    	 */
		    	$scope.freezeBoxWidth = eval($scope.freezeBoxWidth);
		    	$scope.timeOut = 10000;
		    	$scope.checkChangeInterval = 200;
		    	/**
		    	 * 暴露接口
		    	 */
		    	$scope.componentObject = {
		    			/**
		    			 * 冻结窗口
		    			 */
		    			freezeGridWithoutWait:function(data){
		    				$scope.reset();
		    				$scope.timeOut = 50;
		    				$scope.checkChangeInterval = 50;
		    				$scope.freezeGrid();
		    			}
		    			
		    	}
		    	$scope.init = function(){
		    		/**
		    		 *  监听表格dom变化，当内容变化结束的时候，重新生成冻结列和表头
		    		 */
			    	$(elm).bind("contentchange",function(a,b){
		    			$scope.reset();
		    			$scope.freezeGrid();
			    	});
		    	}
		    	/**
		    	 * 重置，清除计数器，清楚冻结表头列
		    	 */
		    	$scope.reset = function(){
					$(elm).parent().scrollTop(0);
					$(elm).parent().scrollLeft(0); 
		    	}
		    	
		    	$scope.freezeGrid = function(){
		    		
		    		$scope.freezeBoxHeight = eval($scope.freezeBoxHeight);
			    	$scope.freezeBoxWidth = eval($scope.freezeBoxWidth);
		    		
		    		var timeColumnWidth,dataColumnWidth,headHeight,headRowlength,timeColumnLength,tableDivWidth,tableDivHeight,headLength;
		    		
		    		/**dataColumnLength,dataCellWidth,timeColumnWidth,freezeBoxWidth
		    		 * 左上角的单元格
		    		 */
		    		var timeHeadCell = $('tr td:first',elm);
		    		/**
		    		 * 除开左上角的单元格外，第一个表头单元格
		    		 */
		    		var dataHeadCell = $($('tr td',elm)[1]);
		    		/**
		    		 * 表头的列数
		    		 */
		    		headLength = $("tr:first td",elm).length - 1;
		    		
		    		var data_main_table = $(elm).parent("div");
		    		var dataRows = $('tr',$(elm));
		    		$scope.initMainTableLayout(elm,headLength,
		    				parseInt($scope.freezeDatacellWidth),
		    				parseInt($scope.freezeTimecellWidth),
		    				parseInt($scope.freezeBoxWidth));
		    		/**
		    		 * 内容单元格的宽度
		    		 */
		    		dataColumnWidth = parseInt(dataHeadCell.outerWidth());
		    		/**
		    		 * 时间列的宽度
		    		 */
		    		timeColumnWidth = parseInt(timeHeadCell.outerWidth());
		    		/**
		    		 * 表头高度
		    		 */
		    		headHeight =  parseInt(timeHeadCell.outerHeight());
		    		/**
		    		 * 表头行数
		    		 */
		    		headRowlength = parseInt($scope.headRowlength);
		    		/**
		    		 * 表格外包div的宽度
		    		 */
		    		tableDivWidth = $scope.freezeBoxWidth;
		    		/**
		    		 * 表格外包div的高度
		    		 */
		    		tableDivHeight = $scope.freezeBoxHeight;
		    		/**
		    		 * 表格宽度
		    		 */
		    		tableWidth = $(elm).outerWidth();
		    		/**
		    		 * 表格高度
		    		 */
		    		tableHeight = $(elm).outerHeight();
		    		/**
		    		 * 要冻结的时间列列数
		    		 */
		    		timeColumnLength = $scope.timeColumnLength?$scope.timeColumnLength:1;
		    		/**
		    		 * 计算各部分的样式
		    		 */
		    		var freezeGridInfo = $freezeGridService.calcFreezeGridInfo(
		    				timeColumnWidth,
		    				timeColumnLength,
		    				dataColumnWidth,
		    				headHeight,
		    				headRowlength,
		    				tableDivWidth,
		    				tableDivHeight,
		    				headLength,
		    				tableWidth,
		    				tableHeight);
		    		
		    		/**
		    		 * 先插入冻结列
		    		 */
		    		var time_columns_table_div = $("<div class='time_columns_table'>").css(freezeGridInfo.time_div_style);
		    		var time_columns_table = $("<table class='zs-data-tab'></table>").appendTo(time_columns_table_div);
		    		
		    		for(var i=0;i<dataRows.length;i++){
		    			var className = $(dataRows[i]).attr("class");
		    			var tds = $("td",$(dataRows[i]));
		    			var tr = $("<tr></tr>");
		    			for(var j=0;j<timeColumnLength;j++){
		    				var td = $(tds[j]).clone();
			    			var tr = tr.append(td);
		    			}
		    			tr.appendTo(time_columns_table).addClass(className)
		    		}
		    		
		    		/**
		    		 * 然后插入冻结表头
		    		 */
		    		var head_row_table_div = $("<div class='head_row_table'>").css(freezeGridInfo.head_div_style);
		    		var head_row_table = $("<table class='zs-data-tab'></table>").appendTo(head_row_table_div).css(freezeGridInfo.head_table_style);
		    		
		    		for(var i=0;i<headRowlength;i++){
		    			var tds = $("td",$(dataRows[i]));
		    			var tr = $("<tr></tr>");
		    			for(var j=0;j<tds.length;j++){
		    				var width = $(tds[j]).css("width");
		    				tr.append($(tds[j]).clone().css("width",width));
		    			}
		    			head_row_table.append(tr);
		    		}		    		
		    		
		    		/**
		    		 * 最后插入冻结角
		    		 */
		    		var corner_cell_table_div = $("<div class='corner_cell_table'>").css(freezeGridInfo.corner_div_style);
		    		var corner_cell_table = $("<table class='zs-data-tab'></table>").appendTo(corner_cell_table_div);
		    		
		    		for(var i=0;i<headRowlength;i++){
		    			var tds = $('td',$(dataRows[i]));
		    			var tr = $("<tr></tr>");
		    			for(var j=0;j<timeColumnLength;j++){
		    				var sourceTd = $(tds[j]);
			    			var width = sourceTd.css("width");
			    			var td = sourceTd.clone().css("width",width);
			    			tr.append(td);
		    			}
		    			tr.appendTo(corner_cell_table);
		    		}
		    		
		    		/**
		    		 * 组装
		    		 */
		    		$(".time_columns_table").remove();
		    		data_main_table.before(time_columns_table_div);
		    		$(".head_row_table").remove();
		    		time_columns_table_div.before(head_row_table_div);
		    		$(".corner_cell_table").remove();
		    		head_row_table_div.before(corner_cell_table_div);
		    		
		    		/**
		    		 * 设置主体样式
		    		 */
		    		data_main_table.css(freezeGridInfo.data_div_style);
		    		
		    		$scope.initScrollEvent(data_main_table);
		    	}
		    	/**
		    	 * 设置表格主体样式
		    	 */
		    	$scope.initMainTableLayout = function(elm,dataColumnLength,dataCellWidth,timeColumnWidth,freezeBoxWidth){
		    		
		    		var data_main_table = $(elm).parent("div").addClass("data_main_table");
		    		
		    		if((dataCellWidth * dataColumnLength+timeColumnWidth) < freezeBoxWidth){
		    			//这里的加一也是为了微调
		    			dataCellWidth = (freezeBoxWidth - timeColumnWidth - 20) / (dataColumnLength);
		    			var trs = $("tr",$(elm));
			    		for(var i=0;i<trs.length;i++){
			    			var tds = $("td",$(trs[i]));
			    			var timeTd = $("td:first",$(trs[i]));
			    		}
		    		}
		    	}
		    	
		    	/**
		    	 * 绑定滚动事件，滚动的时候，同时滚动表头和时间列
		    	 */
		    	$scope.initScrollEvent = function(elm){
		    		$(elm).unbind("scroll").bind("scroll", function(e) {
						 var top=$(elm)[0].scrollTop; 
						 var left=$(elm)[0].scrollLeft; 
						 $(".time_columns_table",$(elm).parent("div"))[0].scrollTop = top;
						 $(".head_row_table",$(elm).parent("div"))[0].scrollLeft = left;
					 })
		    	}
		    	
		    	$scope.init();
	        }
		 } 
	});
	
	Module.service('$freezeGridService',function($waterDataCommon){
		
		/**
		 * 计算表头和时间列冻结的表格信息
		 */
		this.calcFreezeGridInfo = function(timeColumnWidth,timeColumnLength,dataColumnWidth,headHeight,headRowLength,tableDivWidth,tableDivHeight,headLength,tableWidth,tableHeight){
			var freezeGridInfo = {};
			freezeGridInfo.timeColumnWidth = timeColumnWidth;
			freezeGridInfo.dataColumnWidth = dataColumnWidth;
			freezeGridInfo.timeColumnLength = timeColumnLength;
			freezeGridInfo.headHeight = headHeight;
			freezeGridInfo.tableDivWidth = tableDivWidth;
			freezeGridInfo.tableDivHeight = tableDivHeight;
			
			freezeGridInfo.corner_div_style = {
					width:freezeGridInfo.timeColumnWidth * freezeGridInfo.timeColumnLength,
					height:freezeGridInfo.headHeight * headRowLength
				};
			freezeGridInfo.head_div_style = {
					width:freezeGridInfo.tableDivWidth,
					height:freezeGridInfo.headHeight * headRowLength+4,
					top:-freezeGridInfo.headHeight * headRowLength
				};
			freezeGridInfo.time_div_style = {
					width:freezeGridInfo.timeColumnWidth * freezeGridInfo.timeColumnLength,
					height:freezeGridInfo.tableDivHeight,
					top:-(freezeGridInfo.headHeight*headRowLength*2+4),
				};
			//这里的加4是为了修正，具体不知道怎么得出来
			freezeGridInfo.data_div_style = {
					width:freezeGridInfo.tableDivWidth + 16,
					top:-(freezeGridInfo.headHeight*headRowLength*2+freezeGridInfo.tableDivHeight+4),
					height:freezeGridInfo.tableDivHeight+20	
				};
			
			freezeGridInfo.head_table_style = {
				width:tableWidth,
			    margin: 0
			};
			freezeGridInfo.data_table_style = {
					width:tableWidth,
					margin: 0
			};
			
			freezeGridInfo.head_time_td_style = {
					width:freezeGridInfo.timeColumnWidth,
					height:freezeGridInfo.headHeight,
					'text-align':'center'
			};
			freezeGridInfo.head_td_style = {
					width:freezeGridInfo.dataColumnWidth,
					height:freezeGridInfo.headHeight,
					'text-align':'center'
			};
			freezeGridInfo.time_td_style = {
					width:freezeGridInfo.timeColumnWidth,
//					'min-width':freezeGridInfo.timeColumnWidth,
					height:30,
					'text-align':'center'
			};
			freezeGridInfo.data_td_style = {
					width:freezeGridInfo.dataColumnWidth,
//					'min-width':freezeGridInfo.dataColumnWidth,
					'text-align':'center',
					height:'30px'
			};
			
			return freezeGridInfo;
		}
	})
	
	Module.run(function(){
		(function(){

		    var interval;

		    jQuery.event.special.contentchange = {
		        setup: function(){
		            var self = this,
		            $this = $(this),
		            $originalContent = $this.text();
		            interval = setInterval(function(){
		                if($originalContent != $this.text()) {
		                	$originalContent = $this.text();
		                    jQuery.event.handle.call(self, {type:'contentchange'});
		                }
		            },100);
		        },
		        teardown: function(){
		            clearInterval(interval);
		        }
		    };

		})();
	});
}(window, angular));